package util;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {


    public static String getResponse(String url, Map<String, String> params, String appKey, String appSecrty) throws
            IOException {
        String param = ParamEncryptionUtils.sortParam(params, false, false);
        String signed = ParamEncryptionUtils.convert2HmacString(param.getBytes(), appSecrty.getBytes());
        // 组装请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        headers.put("Content-Signature", signed);
        headers.put("Content-AppKey", appKey);
        return post(url, params, headers);

    }

    public static String post(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
        CloseableHttpClient closeableHttpClient = HttpClients.custom().build();
 
        HttpPost post = new HttpPost(url);
        List<NameValuePair> list = new LinkedList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
        post.setEntity(entityParam); 
        // addHeader
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            post.addHeader(entry.getKey(), entry.getValue());
        }
        CloseableHttpResponse response = closeableHttpClient.execute(post);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, "UTF-8");
    }
}
